package org.jumbo.test;

import java.io.File;
import java.util.ArrayList;

public class MediaOrganizerController {
  public static final String DST_DIR_PATH_DEFAULT = "test" + File.separator + "dst";

  public static void main(String[] args) {
    String srcBaseDir = null;
    String dstBaseDir = DST_DIR_PATH_DEFAULT;
    boolean addDayDir = false;
    boolean typeFirst = false;
    for (String arg : args) {
      String[] argParts = arg.split("=");
      if (argParts[0].equals("source_base_dir")) {
        srcBaseDir = argParts[1];
      }
      if (argParts[0].equals("target_base_dir")) {
        dstBaseDir = argParts[1];
      }
      if (argParts[0].equals("add_day_dir")) {
        addDayDir = Boolean.parseBoolean(argParts[1]);
      }
      if (argParts[0].equals("type_first")) {
        typeFirst = Boolean.parseBoolean(argParts[1]);
      }
    }
    if (srcBaseDir.equals(null)) {
      System.out.println("source dir not specified, exit!");
      System.exit(1);
    }    
    System.out.println("source: " + srcBaseDir + " target: " + dstBaseDir);
    
    File srcDir = new File(srcBaseDir);
    if (!srcDir.exists()) {
      System.out.println("source dir is not valid, please rerun with a valid source dir");
      System.exit(1);
    }
    File[] srcFiles = srcDir.listFiles();

    int fileCount = srcFiles.length;
    int i = 0;
    ArrayList<OrganizerWorker> workers = new ArrayList<OrganizerWorker>();
    int j = 0;
    int threadCount = 3;
    long startTimeNano = System.nanoTime();
    while (i < fileCount) {
      int start = i;
      int end = start + fileCount / threadCount - 1;
      if (end >= fileCount) {
        end = fileCount - 1;
      }
      OrganizerWorker worker = new OrganizerWorker(srcBaseDir, dstBaseDir, addDayDir, typeFirst, srcFiles, start, end);
      workers.add(worker);
      worker.start();
      j++;
      i = end + 1;
    }
    System.out.println("Total number of copy worker: " + workers.size());
    for (int k = 0; k < workers.size(); k++) {
      try {
        workers.get(k).join();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    long endTimeNano = System.nanoTime();
    long elapsedTimeSecond = (endTimeNano - startTimeNano) / (1000 * 1000 * 1000);
    System.out.println("It takes " + elapsedTimeSecond + " seconds to copy " + fileCount + " files.");
  }
}
